package com.lgx.mobile.rest.topic;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.exception.DataException;
import com.lgx.mobile.entity.Topic;
import com.lgx.mobile.service.ITopicService;
import com.lgx.right.entity.User;
import com.lgx.right.service.IUserService;

/**
 * 
 * @author xuyichen
 *
 */
@Controller
@RequestMapping("/updateTopic")
public class UpdateTopicController {
	
	private static final Logger logger = Logger.getLogger(UpdateTopicController.class);

	@Autowired
	ITopicService topicService;
	
	public ITopicService getTopicService() {
		return topicService;
	}

	@Autowired
	IUserService userService;

	public IUserService getUserService() {
		return userService;
	}

	/**
	 * 话题修改
	 * @param id id is key
	 * @param name name is key
	 * @param topicContent topicContent is key
	 * @param categoryId categoryId is key
	 * @return 0：失败；1：成功；2：话题不存在；3：参数异常，有参数为空
	 */
	@RequestMapping(value="/{id}/{name}/{topicContent}/{categoryId}",method=RequestMethod.GET)
	@ResponseBody
	public Object getTopic(@PathVariable("id") String id,@PathVariable("name") String name,
							@PathVariable("topicContent") String topicContent,@PathVariable("categoryId") String categoryId){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(name)
				&&StringUtils.isNotBlank(topicContent)&&StringUtils.isNotBlank(categoryId)){
			Topic topic = getTopicService().findTopicById(Long.parseLong(id));
			if(topic != null){
				String status = "0";
				topic.setName(name);
				topic.setTopic(topicContent);
				topic.setCategoryId(Long.parseLong(categoryId));
				try {
					getTopicService().updateTopic(topic);
					status = "1";
				} catch (DataException e) {
					e.printStackTrace();
				}
				return status;
			}else{
				if(logger.isDebugEnabled()){
					logger.debug("updateTopic faild name and topicContent and categoryId is error");
				}
//				"updateTopic faild please check topic is exists";
				return "2";
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("updateTopic faild name and topicContent and categoryId is not filled");
			}
//		    "updateTopic faild please check name and topicContent and categoryId is filled";
			return "3";
		}
	}
	
	/**
	 * 话题增加、删除人
	 * @param id id is key
	 * @param userId userId is key
	 * @param type type is key
	 * 			delete--删除人，add--增加人
	 * @return 0：失败；1：成功；2：该用户不在话题中；3：用户不存在；4：话题不存在；5：参数异常，有参数为空；
	 * 			6：该用户已经在话题中；7:用户不存在；8：话题不存在；9：请检查参数——type是否输入错误
	 */
	@RequestMapping(value="/{id}/{userId}/{type}",method=RequestMethod.GET)
	@ResponseBody
	public Object operateUserFromTopic(@PathVariable("id") String id,@PathVariable("userId") String userId,@PathVariable("type") String type){
		if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(userId)&&StringUtils.isNotBlank(type)){
			//话题删除人
			if(type.equals("delete")){
				Topic topic = getTopicService().findTopicById(Long.parseLong(id));
				if(topic != null){
					User user = getUserService().findUserById(Long.parseLong(userId));
					if(user != null){
						//判断该用户是否应存在于该话题中
						boolean bool = false;
						User u = new User(); 
						Object[] users = topic.getUsers().toArray();
						for(int i=0;i<users.length;i++){
							if( ((User)users[i]).getId() ==  Long.parseLong(userId) ){
								bool = true;
								u = (User)users[i];
							}
						}
						if(bool){
							String status = "0";
							topic.getUsers().remove(u);
							try {
								getTopicService().updateTopic(topic);
								status = "1";
							} catch (DataException e) {
								e.printStackTrace();
							}
							return status;
						}else{
							if(logger.isDebugEnabled()){
								logger.debug("deleteUserFromTopic faild userId is error");
							}
//							"deleteUserFromTopic faild user is not in topic";
							return "2";
						}
					}else{
						if(logger.isDebugEnabled()){
							logger.debug("deleteUserFromTopic faild userId is error");
						}
//						"deleteUserFromTopic faild please check user is exists";
						return "3";
					}
				}else{
					if(logger.isDebugEnabled()){
						logger.debug("deleteUserFromTopic faild id is error");
					}
//					"deleteUserFromTopic faild please check topic is exists";
					return "4";
				}
			}
			//话题添加人
			else if(type.equals("add")){
				Topic topic = getTopicService().findTopicById(Long.parseLong(id));
				if(topic != null){
					User user = getUserService().findUserById(Long.parseLong(userId));
					if(user != null){
						//判断该用户是否应存在于该话题中
						boolean bool = false;
						Object[] users = topic.getUsers().toArray();
						for(int i=0;i<users.length;i++){
							if( ((User)users[i]).getId() ==  Long.parseLong(userId) ){
								bool = true;
							}
						}
						if(!bool){
							String status = "0";
							topic.getUsers().add(user);
							try {
								getTopicService().updateTopic(topic);
								status = "1";
							} catch (DataException e) {
								e.printStackTrace();
							}
							return status;
						}else{
							if(logger.isDebugEnabled()){
								logger.debug("addUserInTopic faild userId is error");
							}
//							"addUserInTopic faild user is already in topic";
							return "6";
						}
					}else{
						if(logger.isDebugEnabled()){
							logger.debug("addUserInTopic faild userId is error");
						}
//						"addUserInTopic faild please check user is exists";
						return "7";
					}
				}else{
					if(logger.isDebugEnabled()){
						logger.debug("addUserInTopic faild id is error");
					}
//					"addUserInTopic faild please check topic is exists";
					return "8";
				}
			}else{
//				"addUserInTopic faild please check type is filled";
				return "9";
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("addUserInTopic faild id and userId and type is not filled");
			}
//		    "addUserInTopic faild please check id and userId and type is filled";
			return "5";
		}
	}
}
